package top.yuzt.animalserver.controller;


import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import top.yuzt.animalserver.common.StpInterfaceImpl;
import top.yuzt.animalserver.entity.User;
import top.yuzt.animalserver.mapper.UserMapper;
import top.yuzt.animalserver.service.impl.UserServiceImpl;

import java.util.List;

/**
 * <p>
 * 管理员 前端控制器
 * </p>
 *
 * @author yuzt
 * @since 2024-05-15
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserServiceImpl userService;

    @PostMapping("/doLogin")
    public SaResult loginAcc(@RequestBody User usertmp){
        User user = userMapper.findByUsername(usertmp.getUsername());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        if (user != null){
            if (BCrypt.checkpw(usertmp.getPassword(), user.getPassword())){
                StpUtil.login(user.getId());
                tokenInfo = StpUtil.getTokenInfo();
                System.out.println(tokenInfo);
                return SaResult.data(tokenInfo).set("user",user);
            }
        }
        return SaResult.error();
    }
    //查询所有
    @SaIgnore
    @GetMapping("/getlist")
    public List<User> getuserlist(){

        return userService.list();
    }
    //新增
    @SaIgnore
    @PostMapping("/save")
    public boolean saveuser(@RequestBody User user){
        String hashedPassword = BCrypt.hashpw(user.getPassword(), BCrypt.gensalt());
        user.setPassword(hashedPassword);
        return userService.save(user);
    }
    //修改
    @SaIgnore
    @PostMapping("/update")
    public boolean updateuser(@RequestBody User user){
        String hashedPassword = BCrypt.hashpw(user.getPassword(), BCrypt.gensalt());
        user.setPassword(hashedPassword);
        return  userService.updateById(user);
    }
    //删除
    @SaIgnore
    @PostMapping("/remove")
    public boolean removeuser(@RequestBody User user){
        return  userService.removeById(user.getId());
    }
    //通过id查找
    @SaIgnore
    @GetMapping("/find")
    public User finduserByID(Integer id){
        return userService.getById(id);
    }
}
